package com.aliyun.messagemgt.rocketmq;

import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.messagemgt.application.service.PushService;
import com.aliyun.messagemgt.common.dto.send.MsgPushDTO;
import com.aliyun.messagemgt.dto.out.MsgPushResponseDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author Qinyuan
 * @date 2025/7/29
 */
@Component
@RocketMQMessageListener(
        topic = "${rocketmq.consumer.topic}",
        consumerGroup = "${rocketmq.consumer.group}"
)
@Slf4j
public class MessageInnerForwardMQConsumer implements RocketMQListener<String> {

    @Autowired
    private PushService pushService;

    @Override
    public void onMessage(String msg) {
        log.info("inner forward receive msg:{}", msg);
        JSONObject jsonObject = JSON.parseObject(msg);
        MockHttpServletRequest mockRequest = new MockHttpServletRequest();
        mockRequest.addHeader("tenantCode", jsonObject.getString("tenantCode"));
        mockRequest.addHeader("secretKey", jsonObject.getString("secretKey"));
        // 绑定请求上下文
        RequestAttributes requestAttributes = new ServletRequestAttributes(mockRequest);
        RequestContextHolder.setRequestAttributes(requestAttributes);
        try {
            MsgPushDTO msgPushDTO = JSON.parseObject(msg, MsgPushDTO.class);
            MultiResponse<SingleResponse<MsgPushResponseDTO>> response = pushService.apiPush(msgPushDTO);
            log.info("async send msg response:{}", JSON.toJSONString(response));
        } catch (Exception e) {
            log.error("async send msg error, msg:{}", msg, e);
        } finally {
            // 清理上下文（防止内存泄漏）
            RequestContextHolder.resetRequestAttributes();
        }
    }
}
